<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="考试/练习名称" prop="examName">
        <el-input v-model="queryParams.examName" placeholder="请输入名称" clearable />
      </el-form-item>
      <el-form-item label="类型" prop="examType">
        <el-select v-model="queryParams.examType" clearable>
          <el-option label="考试" value="exam" />
          <el-option label="练习" value="practice" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable>
          <el-option label="已安排" value="scheduled" />
          <el-option label="进行中" value="in_progress" />
          <el-option label="已完成" value="completed" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="examsList" @selection-change="handleSelectionChange">
      <el-table-column label="考试/练习名称" align="center" prop="examName" />
      <el-table-column label="考试, 练习" align="center" prop="examType" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试时长" align="center" prop="durationMinutes" />
      <el-table-column label="创建者 (学校用户ID)" align="center" prop="createdBySchoolUserId" />
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Exams">
import { listExams, getExams, delExams, addExams, updateExams } from "@/api/schoolmanage/exams"

const { proxy } = getCurrentInstance()

const examsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: useExampleStore().school,
    scenarioId: null,
    labId: null,
    examName: null,
    examType: null,
    startTime: null,
    endTime: null,
    durationMinutes: null,
    status: null,
    parameters: null,
    createdBySchoolUserId: null
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    scenarioId: [
      { required: true, message: "实验场景ID不能为空", trigger: "blur" }
    ],
    examName: [
      { required: true, message: "考试/练习名称不能为空", trigger: "blur" }
    ],
    examType: [
      { required: true, message: "类型: 考试, 练习不能为空", trigger: "change" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态: 已安排, 进行中, 已完成, 已取消不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询考试练习任务列表 */
import { useRoute } from 'vue-router'
import {useExampleStore} from "@/stores/exampleStore.js";

const route = useRoute()

// 获取考试列表
const props = defineProps({
  labId: {
    type: Number,
    default: null // 如果没有 labId，默认 null
  }
})

// 2. 打印 props 检查
console.log("Received labId:", props.labId)

// 3. 在 getList() 中使用
function getList() {
  loading.value = true;
  listExams({
    labId: route.query.labId || props.labId || undefined,
    examName: queryParams.value.examName || undefined,
    examType: queryParams.value.examType || undefined,
    status: queryParams.value.status || undefined,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  }).then(response => {
    examsList.value = response.rows || [];
    total.value = response.total || 0;
  }).finally(() => {
    loading.value = false;
  });
}

// 页面加载时调用
onMounted(() => {
  getList() // 无条件初始加载
})

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function resetQuery() {
  // 重置表单
  proxy.resetForm("queryRef")

  // 重置查询参数（保留必要的参数如labId）
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    schoolId: useExampleStore().school,
    scenarioId: null,
    labId: route.query.labId || props.labId, // 保留labId
    examName: null,
    examType: null,
    startTime: null,
    endTime: null,
    durationMinutes: null,
    status: null,
    parameters: null,
    createdBySchoolUserId: null
  }

  // 重新查询
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.examId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加考试练习任务"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _examId = row.examId || ids.value
  getExams(_examId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改考试练习任务"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["examsRef"].validate(valid => {
    if (valid) {
      if (form.value.examId != null) {
        updateExams(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addExams(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _examIds = row.examId || ids.value
  proxy.$modal.confirm('是否确认删除考试练习任务编号为"' + _examIds + '"的数据项？').then(function() {
    return delExams(_examIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('schoolmanage/exams/export', {
    ...queryParams.value
  }, `exams_${new Date().getTime()}.xlsx`)
}

getList()
</script>
